<template>
  <div>
    <div class="header">
      <span style="width: 60px; text-align: right">关键字</span>
      <el-input placeholder="请输入关键字" v-model="unreturnReq.keyword" style="width: 200px; margin-left: 10px"></el-input>
      <span style="margin-left: 20px">开票日期：</span>
      <el-date-picker v-model="unreturnReq.dealDate1" value-format="yyyy-MM-dd HH:mm:ss" type="date"
        placeholder="选择起始日期"></el-date-picker>
      <span style="margin-left: 10px; margin-right: 10px">至</span>
      <el-date-picker v-model="unreturnReq.dealDate2" value-format="yyyy-MM-dd HH:mm:ss" type="date"
        placeholder="选择截至日期"></el-date-picker>
      <el-button type="primary" style="margin-left: 10px" size="small" @click="getCompanyUnreturnCaseBills()">
        搜索
      </el-button>
      <el-button type="warning" style="margin-left: 10px" size="small" @click="outputUnreturnExcel">
        导出未回款报表
      </el-button>
    </div>
    <div class="main">
      <el-table style="overflow: auto" height="100%" :data="unreturnRes.Items" stripe border highlight-current-row>
        <el-table-column type="index" width="40"></el-table-column>
        <el-table-column label="开票信息">
          <template slot-scope="scope">
            <el-tag :type="scope.row.CSB_Status != 100 ? 'danger' : 'success'">
              {{ scope.row.StatusDesc }}
            </el-tag>
            <div style="text-align: left">
              发票号码:{{ scope.row.CSB_No }}
            </div>
            <div style="text-align: left">
              购买方:{{ scope.row.BuyCompanyName }}
            </div>
            <div style="text-align: left">
              价税合计:{{ scope.row.CSB_Fee }}元
              <span v-if="scope.row.CSB_TaxFee" style="margin-left: 10px">
                税额:{{ scope.row.CSB_TaxFee }}元
              </span>
              <span v-if="scope.row.CSB_WithOutTaxFee" style="margin-left: 10px">
                金额:{{ scope.row.CSB_WithOutTaxFee }}元
              </span>
            </div>
            <div style="text-align: left">
              开票日期:{{ scope.row.CSB_BillDate | formatDate }}
            </div>
            <div style="text-align: left" v-if="scope.row.CSBR_Remark">
              备注:{{ scope.row.CSB_Remark }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="机构回款信息" width="220">
          <template slot-scope="scope">
            <div style="text-align: left" v-if="scope.row.UnreturnSum1 && scope.row.CSB_Status == 100">
              未回款:{{ scope.row.UnreturnSum1 }}元
            </div>
            <div style="text-align: left" v-if="scope.row.ReturnSum">
              已回款:{{ scope.row.ReturnSum1 }}元
            </div>
            <div v-for="item in scope.row.Returns1" :key="item.CSBR_ID" style="margin-top: 5px">
              <el-tag closable type="primary" @close="deleteBillReturn(item.CSBR_ID)">
                {{ item.CSBR_AccountTime | formatDate }}[{{ item.CSBR_Fee }}
                元]
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="案件信息" width="400px">
          <template slot-scope="scope">
            <div v-if="scope.row.CS_No">流水号：{{ scope.row.CS_No }}</div>
            <div v-if="scope.row.CS_InsureCmpCaseNo">
              报案号：{{ scope.row.CS_InsureCmpCaseNo }}
            </div>
            <div v-if="scope.row.CS_AppraiserCmpCaseNo">
              案件编号：{{ scope.row.CS_AppraiserCmpCaseNo }}
            </div>
            <div v-if="scope.row.CS_DisplayName">
              案件名：{{ scope.row.CS_DisplayName }}
            </div>
            <div>差旅性质：{{ scope.row.BelongCase.EXTY_EnumTxt }}</div>
          </template>
        </el-table-column>
        <el-table-column label="其他信息" width="400px">
          <template slot-scope="scope">
            <div v-for="item in scope.row.BelongCase.Employees" :key="item.CSEP_ID">
              {{ item.CSEP_TypeDesc }}：{{
                item.CCV_TargetID == curEmp.CCV_TargetID ? '' : item.CMP_Name
              }}{{ item.USR_Name ? '[' + item.USR_Name + ']' : '' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="120">
          <template slot-scope="scope">
            <div>
              <el-button @click="
                curBill = scope.row
              imageVis = true
                " type="text" size="small" icon="el-icon-search" title="查看案件详情">
                扫描件
              </el-button>
            </div>
            <div>
              <el-button @click="toCase(scope.row.CSB_CaseID)" type="text" size="small" icon="el-icon-search"
                title="查看案件详情">
                案件详情
              </el-button>
            </div>
            <div>
              <el-button v-if="scope.row.CSB_Status != -100" @click="
                curReturn.CSBR_BillID = scope.row.CSB_ID
              curReturn.CSBR_Fee = scope.row.CSB_Fee
              addReturnVis = true
                " type="text" size="small" icon="el-icon-money" title="回款录入">
                机构到账
              </el-button>
            </div>
            <div>
              <el-button @click="curBill = scope.row
              badDeftVis = true" type="text" size="small" icon="el-icon-money" title="标记为坏账">
                坏账
              </el-button>
            </div>
            <div>
              <el-button v-if="scope.row.CBA_FormID" @click="toForm(scope.row.CBA_FormID)" type="text" size="small"
                icon="el-icon-search" title="查看审核流程">
                查看审核流程
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="width: 100%; height: 40px">
      <div style="
          display: flex;
          padding: 10px 50px 0 5px;
          width: auto;
          float: right;
        ">
        <el-pagination layout="total,prev,pager,next,sizes" style="float: right" background
          :current-page.sync="unreturnReq.pageIndex" :total="unreturnRes.Total" :page-size="unreturnReq.pageSize"
          :page-sizes="[5, 10, 15]" @size-change="
            (val) => {
              unreturnReq.pageSize = val
              getCompanyUnreturnCaseBills()
            }
          " @current-change="getCompanyUnreturnCaseBills()"></el-pagination>
      </div>
    </div>

    <el-dialog title="机构回款" :visible.sync="addReturnVis" width="500px" :modal-append-to-body="false" center>
      <el-form label-width="100px" label-position="left" v-if="curReturn">
        <el-form-item label="回款日期">
          <el-date-picker align="right" v-model="curReturn.CSBR_AccountTime" placeholder="请选择回款日期"
            value-format="yyyy-MM-dd HH:mm:ss" type="date"></el-date-picker>
        </el-form-item>
        <el-form-item label="金额(元)">
          <div style="display: flex">
            <el-input-number style="flex: 1" v-model="curReturn.CSBR_Fee" :precision="2"></el-input-number>
          </div>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="curReturn.CSBR_Remark" placeholder="请输入备注" rows="3" type="textarea"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addBillReturn">保存</el-button>
          <el-button type="text" @click="addReturnVis = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog :visible.sync="imageVis" width="60%" :modal-append-to-body="false" center>
      <el-image v-if="curBill && curBill.FL_SrcPath" :src="fileURL + curBill.FL_SrcPath" fit="fill"
        :preview-src-list="[fileURL + curBill.FL_SrcPath]"></el-image>
      <div v-else>未上传发票</div>
    </el-dialog>

    <el-dialog :visible.sync="badDeftVis" width="400px" :modal-append-to-body="false" center title="坏账设置">
      <el-form label-width="50px" label-position="left">
        <el-form-item label="日期">
          <el-date-picker align="right" v-model="badDeftDate" placeholder="请选择坏账日期" value-format="yyyy-MM-dd HH:mm:ss"
            type="date" style="width: 300px"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button @click="setBadDeft" type="primary" icon="el-icon-circle-check" title="确认">
            确认
          </el-button>
          <el-button @click="badDeftVis = false" title="取消">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import {
  getCompanyUnreturnCaseBills,
  addBillReturn,
  deleteBillReturn,
  setBadDeft,
} from '@/api/finance/caseBillReturn'
import { baseURL, fileRoot, tokenName, empIdName } from '@/config'
import axios from 'axios'

export default {
  data: function () {
    return {
      unreturnReq: {
        pageIndex: 1,
        pageSize: 5,
        dealDate1: null,
        dealDate2: null,
        keyword: null,
      },
      unreturnRes: {
        Items: [],
        Total: 0,
      },

      curBill: null,
      curReturn: {},
      fileURL: baseURL + fileRoot,
      addReturnVis: false,
      imageVis: false,
      badDeftDate: null,
      badDeftVis: false,
    }
  },
  computed: {
    ...mapGetters({
      curEmp: 'user/curEmp',
    }),
  },
  methods: {
    getCompanyUnreturnCaseBills() {
      getCompanyUnreturnCaseBills(this.unreturnReq).then(({ data }) => {
        this.unreturnRes = data
      })
    },
    toForm: function (formId) {
      this.$router.push({
        name: 'formInfoPage',
        query: { formId },
      })
    },
    toCase: function (caseId) {
      this.$router.push({
        name: 'caseInfoPage',
        query: { caseId },
      })
    },
    addBillReturn: function () {
      //机构回款
      this.curReturn.CSBR_Type = 1
      addBillReturn(this.curReturn).then(() => {
        this.getCompanyUnreturnCaseBills()
        this.addReturnVis = false
        this.$router.push({
          name: 'caseBillReturnPage',
        })
      })
    },
    deleteBillReturn(id) {
      this.$confirm(`是否删除该回款记录？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deleteBillReturn(id).then(() => {
          this.getCompanyUnreturnCaseBills()
        })
      })
    },
    setBadDeft(id) {
      if (this.curBill == null) {
        return
      }
      this.$confirm(`确定将该发票标记为坏账？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        setBadDeft(this.curBill.CSB_ID, true, this.badDeftDate).then(() => {
          this.getCompanyUnreturnCaseBills()
          this.badDeftVis = false
        })
      })
    },
    outputUnreturnExcel() {
      var config = {
        baseURL,
        headers: {},
        responseType: 'blob',
      }
      config.headers[tokenName] = this.$store.getters['user/accessToken']
      config.headers[empIdName] = this.$store.getters['user/curEmp'].EMP_ID
      axios
        .post(
          '/api/Finance/CaseBillReturnStas/OutputUnreturnCaseBillExcel',
          this.unreturnReq,
          config
        )
        .then((response) => {
          var blob = new Blob([response.data])
          var downloadElement = document.createElement('a')
          var href = window.URL.createObjectURL(blob) //创建下载的链接
          downloadElement.href = href
          downloadElement.download = '未回款报表.xls' //下载后文件名
          document.body.appendChild(downloadElement)
          downloadElement.click() //点击下载
          document.body.removeChild(downloadElement) //下载完成移除元素
          window.URL.revokeObjectURL(href) //释放掉blob对象
        })
        .catch((error) => {
          console.log('response: ', error)
        })
    },
  },
  created: function () {
    var data = this.$store.getters['pagination/getRoutePage'](this.$route)
    Object.assign(this.$data, data)
    this.getCompanyUnreturnCaseBills()
  },
  beforeRouteLeave(to, from, next) {
    this.$store.dispatch('pagination/setRoutePage', {
      route: this.$route,
      pageData: this.$data,
    })
    next()
  },
}
</script>
<style scoped>
.header {
  width: 100%;
  padding-top: 10px;
  padding-bottom: 10px;
  height: auto;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  background: #ffffff;
  border-radius: 5px;
  border-bottom: #f4f8ff 2px solid;
  display: flex;
  margin-bottom: 11px;
  align-items: center;
}

.main {
  height: calc(75vh - 60px);
  overflow: auto;
}
</style>
